package com.spa.application.service.admin;

import cn.hutool.core.util.ObjectUtil;
import com.spa.application.dto.admin.ResourceDTO;
import com.spa.domain.entity.Resource;
import com.spa.infrastructure.mapper.ResourceMapStruct;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单编排.
 *
 * @author liangjun
 */
@Component
public class MenuAssembler {

    /**
     * 转换菜单.
     *
     * @return 菜单列表
     */
    public List<ResourceDTO> resourceDTOList(List<Resource> resourceList) {
        List<ResourceDTO> resourceDTOList = ResourceMapStruct.INSTANCE.toResourceDTOList(resourceList);
        List<ResourceDTO> topList = resourceDTOList.stream()
                .filter(resourceDTO -> resourceDTO.getParentId() == 0)
                .collect(Collectors.toList());
        resourceDTOList.removeAll(topList);
        fill(topList, resourceDTOList);
        return topList;
    }

    private void fill(List<ResourceDTO> parentList, List<ResourceDTO> unprocessedList) {
        parentList.stream()
                .map(parent -> fillChild(parent, unprocessedList))
                .filter(childList -> !childList.isEmpty())
                .forEach(childList -> {
                    unprocessedList.removeAll(childList);
                    fill(childList, unprocessedList);
                });
    }

    private List<ResourceDTO> fillChild(ResourceDTO parent, List<ResourceDTO> unprocessedList) {
        List<ResourceDTO> child = unprocessedList.stream()
                .filter(unprocessed -> {
                    boolean f = ObjectUtil.equals(unprocessed.getParentId(), parent.getId());
                    return f;
                })
                .collect(Collectors.toList());
        parent.setChildren(child);
        return child;
    }

}
